package com.gewu.teday.fragmnet

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ImageSpan
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import com.gewu.teday.R
import com.gewu.teday.activity.TixianListActivity
import com.gewu.teday.adapter.ItemBenan
import com.gewu.teday.adapter.MoenyListAdapter
import com.gewu.teday.adapter.TixianListBean
import com.gewu.teday.bean.DataBeans
import com.gewu.teday.utils.GwDialog
import com.gewu.teday.utils.SpUtils
import com.gewu.teday.utils.Util
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import kotlinx.android.synthetic.main.zhengti_fragmnet.view.*
import kotlin.collections.ArrayList
import kotlin.math.floor


class ZhengTiFragment : BaseFragment(), MoenyListAdapter.Onclick {

    private var linechart: LineChart? = null
    private var listAda = ArrayList<ItemBenan>()
    private var moenyListAdapter: MoenyListAdapter? = null

    override fun getLayoutId(): Int = R.layout.zhengti_fragmnet

    @SuppressLint("SetTextI18n")
    override fun initView() {
        view?.text_top?.text = "0${resources.getString(R.string.top_text)}"
        view?.tv_money?.text = "0"
        initAdapter()

        val afterAndbeforeTimeCalendar = Util.afterAndbeforeTimeCalendar()
        if (afterAndbeforeTimeCalendar) {
            if (decodeParcelable != null && decodeParcelable!!.money.toInt() != 0) {
                view?.tv_gotixian?.background = resources.getDrawable(R.drawable.tixianok_shape)
            }
        } else {
            view?.tv_gotixian?.background = resources.getDrawable(R.drawable.tixianno_shape)
        }

        view?.tv_gotixian?.setOnClickListener {

            if (afterAndbeforeTimeCalendar) {
                val decodeParcelable = SpUtils.instances?.decodeParcelable("data", DataBeans::class.java)
                val tixianListBeans = SpUtils.instances?.decodeParcelable("banck", TixianListBean::class.java)
                if (decodeParcelable != null && decodeParcelable.money.toFloat() != 0f) {
                    showTixianWindow(decodeParcelable, tixianListBeans)
                } else {
                    Toast.makeText(context, "提现金额为0元", Toast.LENGTH_SHORT).show()
                }
            } else {
                val gwDialog = context?.let { it1 -> GwDialog(it1) }
                val layoutBuilder = gwDialog?.LayoutBuilder()
                val create = layoutBuilder?.create(
                    R.layout.tixian_tips,
                    true,
                    Gravity.CENTER,
                    R.drawable.shape_tixian,
                    context?.let { it1 -> gwDialog.getScreenW(it1) }!! / 10 * 5
                )
                create?.show()
                view?.postDelayed(
                    { create?.dismiss() }, 2000
                )
            }
        }
        view?.tixianHis?.setOnClickListener {
            startActivity(Intent(context, TixianListActivity().javaClass))
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showTixianWindow(decodeParcelables: DataBeans, tixianListBeans: TixianListBean?) {
        val gwDialog = context?.let { it1 -> GwDialog(it1) }
        val layoutBuilder = gwDialog?.LayoutBuilder()
        val create = layoutBuilder?.create(
            R.layout.tixian_bottom,
            true,
            Gravity.BOTTOM,
            R.drawable.bottom_shape,
            context?.let { gwDialog.getScreenW(it) }!!,
            (context?.let { gwDialog.getScreenH(it) }!! / 10 * 3.5).toInt()
        )
        create?.show()
        val viewLay = layoutBuilder?.getView()
        val tixiantips = viewLay?.findViewById<TextView>(R.id.tixiantips)
        val countnums = viewLay?.findViewById<TextView>(R.id.countnums)
        val yunums = viewLay?.findViewById<TextView>(R.id.yunums)
        val ontixianCount = viewLay?.findViewById<TextView>(R.id.ontixianCount)
        val tixian_no = viewLay?.findViewById<TextView>(R.id.tixian_no)
        val tixian_ok = viewLay?.findViewById<TextView>(R.id.tixian_ok)

        if (tixiantips != null && yunums!=null && countnums!=null) {
            tixiantips.text = "确认提现${String.format("%.2f", decodeParcelables.money.toFloat())}元?"
            yunums.text = String.format("%.2f", (decodeParcelables.money.toFloat() * 0.08)) + "元"
            countnums.text = String.format("%.2f", (decodeParcelables.money.toFloat() * 0.08 + decodeParcelables.money.toFloat())) + "元"
        }

        var count: Float = 0F

        if (tixianListBeans != null && tixianListBeans.list.size!=0) {
            for (i in 0 until tixianListBeans.list.size) {
                count += tixianListBeans.list[i].bankMoney.toString().toFloat()
            }
            ontixianCount!!.text = "本月已提现${String.format("%.2f", count)}元(税前),扣税方法请"
        } else {
            ontixianCount!!.text = "本月已提现${0}元(税前),扣税方法请"
        }

        tixian_no?.setOnClickListener { create?.dismiss() }

        tixian_ok?.setOnClickListener {
            view?.tv_money!!.text = "0"
            decodeParcelables.money = 0.toString()
            SpUtils.instances?.encodeParcelable("data", decodeParcelables)
            view?.tv_gotixian?.background = resources.getDrawable(R.drawable.tixianno_shape)
            create?.dismiss()
            Toast.makeText(context,"提现成功",Toast.LENGTH_SHORT).show()
        }

    }

    override fun initData() {
            decodeParcelable?.let {
                data(it)
                initSpinner(it)
            }
    }

    private fun initAdapter() {
        moenyListAdapter = MoenyListAdapter(this)
        view?.listview?.adapter = moenyListAdapter
        view?.listview?.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
    }

    var xAxis: XAxis? = null

    private fun initLineChart(dataBeans: DataBeans) {
        linechart = view?.linechart
        linechart?.legend?.isEnabled = false
        linechart?.description?.isEnabled = false
        linechart?.isDragEnabled = false
        linechart?.isDoubleTapToZoomEnabled = false;//双击缩放
        linechart?.setScaleEnabled(false);//启动缩放上的2个轴
        linechart?.setTouchEnabled(false);//设置是否可以触摸

        xAxis = linechart?.xAxis
        xAxis?.axisMinimum = -0.5f;
        xAxis?.setDrawAxisLine(true);
        xAxis?.position = XAxis.XAxisPosition.BOTTOM;
        xAxis?.setDrawGridLines(false)
        xAxis?.textColor = resources.getColor(R.color.huise)
        xAxis?.granularity = 1F

        xAxis?.valueFormatter = object : ValueFormatter() {
            override fun getAxisLabel(value: Float, axis: AxisBase?): String {
                return Util.formartTime(dataBeans.mothlist.reversed()[dataBeans.mothlist.size - 7 + value.toInt()])
            }
        }

        val yAxis = linechart?.axisLeft;//获取左轴
        linechart?.axisRight?.isEnabled = false;//隐藏右轴 默认显示
        yAxis?.setDrawAxisLine(false);//绘制X轴，默认为true
        yAxis?.setDrawGridLines(true);//绘制网格线 默认为true
        yAxis?.enableGridDashedLine(10f, 10f, 0f)
        yAxis?.gridColor = resources.getColor(R.color.huise2)
        yAxis?.textSize = 11f;//设置轴标签的文字大小。
        yAxis?.textColor = resources.getColor(R.color.huise)
        yAxis?.spaceTop = 10F
    }

    private fun setLineDate(dataBeans: DataBeans) {
        val yValue: ArrayList<Entry> = ArrayList()
        val xValue: ArrayList<Float> = ArrayList()
        for (i in 0 until 7) {
            xValue.add(dataBeans.moneylist[i].toFloat())
        }
        val reversed = xValue.reversed()
        for (i in 0 until 7) {
            yValue.add(Entry(i.toFloat(), reversed[i]))
        }

        val lineData = LineData()
        val dataSet = LineDataSet(yValue, "lineName")
        view?.linechart?.xAxis?.axisMaximum = (xValue.size - 0.5).toFloat()
        dataSet.lineWidth = 1f
        dataSet.isHighlightEnabled = false
        dataSet.mode = LineDataSet.Mode.LINEAR
        dataSet.color = Color.parseColor("#E99563")
        dataSet.setDrawValues(false)
        dataSet.setDrawCircles(false)
        dataSet.setDrawCircleHole(false)
        dataSet.axisDependency = YAxis.AxisDependency.LEFT

        lineData.addDataSet(dataSet)
        lineData.notifyDataChanged()
        linechart?.data = lineData
        linechart?.invalidate()
        linechart?.notifyDataSetChanged()
    }

    private fun initSpinner(dataBeans: DataBeans) {
        val starArray = arrayOf("近 7 天", "近30天", "近三月")
        try {
            requireView().spinner.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, starArray)
            dataBeans.let { requireView().spinner.setSelection(it.type) }
            requireView().spinner.onItemSelectedListener = (object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long,
                ) {
                    view?.spinner?.setSelection(position)
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                }

            })
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    override fun showDialog(itemBenan: ItemBenan, index: Int) {
        val build = context?.let { GwDialog(it).LayoutBuilder() }
        val create =
            build?.create(R.layout.bottom_dialog, true, Gravity.BOTTOM, R.drawable.bottom_shape)
        create?.show()
        val view = build?.getView()
        view?.findViewById<ImageView>(R.id.cancel)?.setOnClickListener { create?.cancel() }
        view?.findViewById<TextView>(R.id.tv_spmoney)?.text = "${0}元"

        if (Util.afterTimeCalendar()) {
            view?.findViewById<TextView>(R.id.tv_weimoney)?.text = "${itemBenan.count}元"
        } else {
            if (index == 0) {
                view?.findViewById<TextView>(R.id.tv_weimoney)?.text = "待更新"
            } else {
                view?.findViewById<TextView>(R.id.tv_weimoney)?.text = "${itemBenan.count}元"
            }
        }
    }


    @SuppressLint("SetTextI18n", "UseCompatLoadingForDrawables")
    fun data(dataBeans: DataBeans) {
        val afterAndbeforeTimeCalendar = Util.afterAndbeforeTimeCalendar()
        if (afterAndbeforeTimeCalendar) {
            if (dataBeans.money.toFloat() != 0f) {
                view?.tv_gotixian?.background = resources.getDrawable(R.drawable.tixianok_shape)
            }
        } else {
            view?.tv_gotixian?.background = resources.getDrawable(R.drawable.tixianno_shape)
        }

        hander?.postDelayed({
            setToptext(dataBeans)
        }, 500)

        initLineChart(dataBeans)

        hander?.postDelayed({
            initSpinner(dataBeans)
            setLineDate(dataBeans)
        }, 600)

        hander?.postDelayed({
            setAdapter(dataBeans)
        }, 700)
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setAdapter(dataBeans: DataBeans) {
        if (!listAda.isNullOrEmpty()) {
            listAda.clear()
        }
        moenyListAdapter?.clearListItem()
        val mothlist = dataBeans.mothlist
        for (i in 0 until mothlist.size) {
            val toString = dataBeans.moneylist[i].toString()
            moenyListAdapter?.addListItem(ItemBenan(mothlist[i], toString))
        }
        moenyListAdapter?.notifyDataSetChanged()
    }

    @SuppressLint("SetTextI18n")
    private fun setToptext(decodeParcelable: DataBeans) {
        view?.text_top?.postDelayed(Runnable {
            view?.tv_money?.text =
                if (decodeParcelable.money.isEmpty()) "0" else String.format(
                    "%.2f",
                    decodeParcelable.money.toFloat()
                )
            val string = context?.resources?.getString(R.string.top_text)
            val lineWidth: Float = requireView().text_top.layout.getLineWidth(0)
            val lineEnd: Int = requireView().text_top.layout.getLineEnd(0)
            val widthPerChar = lineWidth / (lineEnd + 1)
            val numberPerLine = floor((requireView().text_top.width / widthPerChar).toDouble()).toInt()
            val stringBuilder = StringBuilder(string).insert(numberPerLine - 1, "")
            val spannableString = SpannableString("${if (decodeParcelable.videoNum.isEmpty()) "0" else decodeParcelable.videoNum}${stringBuilder}")
            val drawable = resources.getDrawable(R.drawable.right_ic)
            drawable.setBounds(10, 19, drawable.intrinsicWidth, drawable.intrinsicHeight)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                val imageSpan = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)
                spannableString.setSpan(
                    imageSpan,
                    spannableString.length - 1,
                    spannableString.length,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                )
                view?.text_top?.text = spannableString
            }
        }, 200)
    }


}

